<?php
declare (strict_types=1);

namespace common\middleware;

use think\facade\Session;
use function json;

class Auth
{
    /**
     * 登录鉴权
     *
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json|\think\response\Redirect
     */
    public function handle($request, \Closure $next)
    {
        $adminId = session('admin_id');
        if ($adminId) {
            $adminInfo = cache('Admin:' . $adminId);
            if ($adminInfo) {
                $adminInfo = json_decode($adminInfo, true);
            }

            if ($adminInfo && isset($adminInfo['id'])) {
                $request->ADMIN_INFO = $adminInfo;
                return $next($request);
            }
        }

        if ($request->isAjax()) {
            return json([
                'code' => 50101,
                'msg'  => '登录已过期',
                'data' => []
            ]);
        } else {
            return redirect('/login');
        }
    }
}